<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 * 商机管理
 */
class BusinessProduct Extends Model
{
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'qingdongams_business_product';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    //产品
    public function product(){
        return $this->belongsTo(Product::class,'product_id','id',  [], 'LEFT')->setEagerlyType(0);
    }
    //上级
    public function business(){
        return $this->belongsTo(Business::class,'business_id','id');
    }
    //产品
    public function productOne() {
        return $this->hasOne(Product::class, 'id', 'product_id')->bind('name,img,num,unit,wholesale');
    }

    //产品详情
    public function productinfo(){
        return $this->belongsTo(Product::class,'product_id','id')
            ->field('id,goods_id,name,type,unit,cost_price,price,wholesale')->with(['goods']);
    }
    //获取产品配置
    public function getPartsAttr($value)
    {
        $value = json_decode($value, true);
        if(empty($value)){
            return $value;
        }
        $part_ids = [];
        foreach ($value as $v) {
            $part_ids[] = $v['part_id'];
        }
        $model=new ProductPart();
        $product_part = $model->where(['id' => ['in', $part_ids]])->column('name,img', 'id');
        foreach ($value as $k => $v) {
            if (isset($product_part[$v['part_id']])) {
                $v['name'] = $product_part[$v['part_id']]['name'];
                $v['img'] = cdnurl($product_part[$v['part_id']]['img'], true);
            }
            $value[$k] = $v;
        }
        return $value;
    }

    //导入
    public static function importProduct($data) {

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->insertAll($data);
        return $result;
    }
}